package com.ruoyi.system.service.impl;

import com.ruoyi.common.enums.DrillEnum;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.DefDrill;
import com.ruoyi.system.domain.dto.OpenApiDTO;
import com.ruoyi.system.domain.vo.DefDrillByRoleVO;
import com.ruoyi.system.mapper.DefDrillMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.IDefDrillService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 演练管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-08
 */
@Service
public class DefDrillServiceImpl implements IDefDrillService 
{
    private static final Log log = LogFactory.getLog(DefDrillServiceImpl.class);
    @Autowired
    private DefDrillMapper defDrillMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 查询演练管理
     * 
     * @param drillId 演练管理主键
     * @return 演练管理
     */
    @Override
    public DefDrill selectDefDrillByDrillId(Integer drillId)
    {
        return defDrillMapper.selectDefDrillByDrillId(drillId);
    }

    /**
     * 查询演练管理列表
     * 
     * @param defDrill 演练管理
     * @return 演练管理
     */
    @Override
    public List<DefDrill> selectDefDrillList(DefDrill defDrill)
    {
        return defDrillMapper.selectDefDrillList(defDrill);
    }

    /**
     * 新增演练管理
     * 
     * @param defDrill 演练管理
     * @return 结果
     */
    @Override
    public int insertDefDrill(DefDrill defDrill)
    {
        defDrill.setCreateTime(DateUtils.getNowDate());
        return defDrillMapper.insertDefDrill(defDrill);
    }

    /**
     * 修改演练管理
     * 
     * @param defDrill 演练管理
     * @return 结果
     */
    @Override
    public int updateDefDrill(DefDrill defDrill)
    {
        defDrill.setUpdateTime(DateUtils.getNowDate());
        return defDrillMapper.updateDefDrill(defDrill);
    }

    /**
     * 批量删除演练管理
     * 
     * @param drillIds 需要删除的演练管理主键
     * @return 结果
     */
    @Override
    public int deleteDefDrillByDrillIds(Integer[] drillIds)
    {
        return defDrillMapper.deleteDefDrillByDrillIds(drillIds);
    }

    /**
     * 删除演练管理信息
     * 
     * @param drillId 演练管理主键
     * @return 结果
     */
    @Override
    public int deleteDefDrillByDrillId(Integer drillId)
    {
        return defDrillMapper.deleteDefDrillByDrillId(drillId);
    }

    @Override
    public List<DefDrillByRoleVO> listByRole(DefDrill defDrill) {
        Long userId = SecurityUtils.getUserId();
        List<Long> roleIds = sysRoleMapper.selectRoleListByUserId(userId);
        // 查找是否有超级管理员或系统管理员角色
        Optional<RoleEnum> adminRole = roleIds.stream()
                .map(RoleEnum::getByCode)
                .filter(roleEnum -> roleEnum == RoleEnum.SUPER_ADMIN || roleEnum == RoleEnum.SYSTEM)
                .findFirst();

        if (adminRole.isPresent()) {
            RoleEnum roleEnum = adminRole.get();
            List<DefDrillByRoleVO> objects = new ArrayList<>();
            DefDrillByRoleVO defDrillByRoleVO = new DefDrillByRoleVO();
            defDrillByRoleVO.setRoleId(Math.toIntExact(roleEnum.getCode()));
            defDrillByRoleVO.setRoleName(roleEnum.getDescription());
            objects.add(defDrillByRoleVO);

            return objects;  // 如果是超级管理员或系统管理员，返回角色信息
        }

        return defDrillMapper.selectDefDrillListWithRoleOrDrill(userId, null);
    }

    @Override
    public List<DefDrill> drill(OpenApiDTO dto) {
        return defDrillMapper.drill(dto);
    }

    // 每30分钟执行一次
    //@Scheduled(cron = "0 0/30 * * * ?")
    @Scheduled(cron = "0 * * * * ?")
    private void updateStatus() {
        log.info("开始更新演练状态======================");
        List<DefDrill> inProgressDrills = defDrillMapper.selectInProgressDrills();
        // 获取当前时间
        Date now = new Date();

        // 遍历所有正在进行的演练
        inProgressDrills.forEach(drill -> {
            if (now.before(drill.getStartTime())) {
                // 当前时间早于演练开始时间，状态为未开始
                drill.setDrillStatus((long) DrillEnum.NOT_STARTED.getCode());  // 0表示未开始
            } else if (now.after(drill.getEndTime())) {
                // 当前时间晚于演练结束时间，状态为已结束
                drill.setDrillStatus((long) DrillEnum.FINISHED.getCode());  // 2表示已结束
            } else {
                // 当前时间在演练的开始和结束时间之间，状态为进行中
                drill.setDrillStatus((long) DrillEnum.IN_PROGRESS.getCode());  // 1表示进行中
            }
            // 更新数据库中的状态
            defDrillMapper.updateDrillStatus(drill.getDrillId(), Math.toIntExact(drill.getDrillStatus()));
        });
    }
}
